<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p>history Api test</p>
  <button id="btn">修改url</button>
</body>

<script>
  // 初次加载，获取path
  document.addEventListener('DOMContentLoaded', () => {
    console.log('load:', location.pathname)
  })

  // 打开一个新的路由
  // [注意] 使用pushState方式，浏览器不会刷新页面
  document.getElementById('btn').addEventListener('click', () => {
    const state = { name: 'page1' }
    console.log('切换路由到 => ', 'page1')
    history.pushState(state, '', 'page1')
  })

  // 浏览器监听前进/后退
  window.onpopstate = event => {
    console.log('onpopstate: ', event.state, location.pathname)
  }

</script>

</html>